const { Op } = require('sequelize')
const Cart = require('../model/cart.model');
const Goods = require('../model/goods.model');

class CartServic {
    async createOrUpdate(user_id, goods_id) {
        // 根据user_id和goods_id同时查找(查找)
        let res = await Cart.findOne({
            where: {
                [Op.and]: {
                    user_id,
                    goods_id
                }
            }
        });

        if (res) {
            // 已经存在一跳记录  更新数据
            await res.increment('number')
            return await res.reload()
        } else {
            // 新增一条数据
            return await Cart.create({
                user_id,
                goods_id
            })
        }

    }
    async findCarts(page, pageSize) {
        // 重点关联表
        const offset = (page - 1) * pageSize
        const { count, rows } = await Cart.findAndCountAll({
            attributes: ['id', 'number', 'selected'],
            offset: offset,
            limit: pageSize * 1,
            include: {
                model: Goods,
                as: 'goods_info',
                // 筛选出来字段
                attributes: ['id', 'goods_name', 'goods_price', 'goods_img']
            }
        })
        return {
            page,
            pageSize,
            total: count,
            list: rows
        }
    }
    async updateCarts(params) {
        const { id, number, selected } = params;

        const res = await Cart.findByPk(id);
        if (!res) return '';
        number !== undefined ? (res.number = number) : ''
        if (selected !== undefined) {
            res.selected = selected;
        }

        return await res.save()
    }

    async removeCarts(ids) {
        return await Cart.destroy({
            where: {
                id: {
                    [Op.in]: ids
                },
            },
        })

    }

    async selectAllCarts(user_id, selected) {
        return await Cart.update({ selected: selected }, {
            where: {
                user_id
            }
        })
    }

}

module.exports = new CartServic()